package com.hw01.utils;

import java.io.InputStream;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;

/**
 * 阿里OSS云存储工具类
 */
public class OSSUtils {

    // 设置Endpoint、AccessKeyId和AccessKeySecret
    private static final String ENDPOINT = "oss-cn-beijing.aliyuncs.com";
    private static final String ACCESS_KEY_ID = "LTAI5tN9sk5okEPu8cX1cwDN";
    private static final String ACCESS_KEY_SECRET = "8Tiv71GDbOC5gmqVZTMfp5fiZyOzkg";
    private static final String BUCKET_NAME = "hw-01";

    private static final String URL = "https://hw-01.oss-cn-beijing.aliyuncs.com/";

    public static final String DEFAULT_PHOTO = "https://hw-01.oss-cn-beijing.aliyuncs.com/default.jpeg";

    // 上传
    public static String upload(InputStream is, String objectName) {
        // 创建OSSClient实例
        OSS ossClient = new OSSClientBuilder().build(ENDPOINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET);
        try {
            // 调用putObject方法上传文件
            PutObjectResult putResult = ossClient.putObject(new PutObjectRequest(BUCKET_NAME, objectName, is));

            System.out.println("ETag:" + putResult.getETag());

            return URL + objectName;

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 关闭OSSClient
            ossClient.shutdown();
        }
        return null;
    }

    public static void main(String[] args) {
        try (InputStream is = OSSUtils.class.getResourceAsStream("/template/default.jpeg")) {

            String fileName = "default.jpeg";

            OSSUtils.upload(is, fileName);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
